﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Xml.Linq;
using System.Configuration;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using System.Globalization;
using System.Linq;

namespace qlist
{
    class qlist
    {
        
        // set these constants with your values to run the sample.
        private const string _serviceName = "geres3";
        private const string _storageacc = "<storage account name>";
        private const string _storagekey = "<storage account key>";
        //Connection Strings

        private const string _connectionstring = "<storage connection string>";


        static int Main(string[] args)
        {
            string qname = "";
           
            if (args.Length!=1)
            {
                Console.WriteLine("Usage: qlist <queue name>");
                return 1;
            }
            else
            {
                qname = args[0];
            }
            
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionstring);

            CloudQueueClient queueclient = storageAccount.CreateCloudQueueClient();
            CloudQueue taskqueue = queueclient.GetQueueReference(qname);
            if (!taskqueue.Exists())
            {
                Console.WriteLine("Task queue: {0} does not exist.", qname);
                return 1;
            }
            

            taskqueue.FetchAttributes();
            int nofmsg = (int)taskqueue.ApproximateMessageCount;

            if (nofmsg==0)
            {
                Console.WriteLine("No messages in queue: {0}", qname);
                return 0;
            }
            
            Console.WriteLine("{0} messages in queue: {1}. Max. 32 can be displayed.", nofmsg, qname);
            
            IEnumerable<CloudQueueMessage> messages = taskqueue.PeekMessages((nofmsg <= 32) ? nofmsg : 32);

            Console.WriteLine("JobID\t\t\tTimeIn\t\t\t\tCommand");
            
            foreach (CloudQueueMessage message in messages)
            {
                string[] content = message.AsString.Split(' ');
                string jobid = content[0];
                string command = content[1];
                string pars = message.AsString.Substring(message.AsString.IndexOf(content[2]));
                Console.WriteLine("{0}\t{1}\t{2}", jobid, message.InsertionTime, command + " " + pars);
            }
            return 0;


        }
    }
}
